package jolly.clipboard.controllers;

/**
 * Created by IntelliJ IDEA.
 * User: david
 * Date: 12/17/11
 * Time: 3:50 AM
 * To change this template use File | Settings | File Templates.
 */

import jolly.clipboard.dao.ClipboardFacade;
import jolly.clipboard.domain.Clipboard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/")
@SessionAttributes("clipboard")
public class HomeController {

    @Autowired
    ClipboardFacade clipboardFacade;

    @RequestMapping(method = RequestMethod.GET)
    public String renderHomePage(@RequestParam(value = "u", required = false) String url,
                                 Model model) {

        if (url != null) {
            System.out.println("Appending : " + url);
            clipboardFacade.save(url);
        }
        
        clipboardFacade.startNewSession();

        model.addAttribute("clipboard", clipboardFacade.getClipboard());
        return "home";

    }

    @RequestMapping(method = RequestMethod.POST)
    public String saveClipboard(@RequestParam(value = "u", required = false) String url,
                                @ModelAttribute("clipboard") Clipboard clipboard,
                                Model model) {

        // Intentionally ignore url.
        
        if (clipboardFacade.isWriteSafe()) {
            9
        }

        if (clipboardFacade.getClipboard().getText().equals(clipboard.getText())) {
            // Do nothing.
            System.out.println("Clipboard has not changed... doing nothing.");

        } else {
            System.out.println("Setting new clipboard.");
            clipboardFacade.save(clipboard);
        }

        model.addAttribute("clipboard", clipboard);

        return "home";
    }

}